<template>
  <div v-if="isShowSkeleton" class="mt20">
    <van-skeleton title :row="5" />
  </div>
  <div v-else class="pageBox">
    <div class="favorite-wrapper" ref="favoriteScrollWrap">
      <van-empty description="暂无数据" v-if="!total" />

      <div class="favorite">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list v-if="total > 0" v-model:loading="loading" :finished="finished" finished-text="没有更多了"
            v-model:error="error" error-text="请求失败，点击重新加载" @load="onLoad" :offset="50">
            <a :href="`/menu/detail/${item.menu_id}`" v-for="item in list" :key="item.id"
              class="food-item bg-ff flexBox aiCenter">
              <div class="img-box">
                <img :src="handleImgSrc(item.menu_info.photo_url)" alt="" class="food-img">
              </div>
              <div class="flexItem ml20">
                <div class="fs28">{{ item.menu_info.name }}</div>
                <div class="fs26 f600 c-f00">¥{{ item.menu_info.fee }}</div>
              </div>
              <van-icon name="like" size="18" color="#FF5000" @click.stop.prevent="handleFavorite(item)" />
            </a>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { cancelFavorite, favoriteList } from '@/api/menu'
import { onMounted, onUnmounted, reactive, ref } from 'vue'
import { handleImgSrc } from '@/utils'
import { FavoriteListType } from '@/types/userTypes'
// import router from '@/router'

const list = ref<FavoriteListType[]>([])
const total = ref(0)
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(true)
const error = ref(false)
const isShowSkeleton = ref(true)
const favoriteScrollWrap = ref<HTMLDivElement | null>(null)
const pageData = reactive({
  page: 1,
  pageSize: 10
})

const getList = async () => {
  try {
    const { data } = await favoriteList(pageData)
    if (data.code === 0) {
      isShowSkeleton.value = false
      if (pageData.page === 1) {
        list.value = data.data.entries
      } else {
        list.value = [...list.value, ...data.data.entries]
      }

      total.value = data.data.total
      finished.value = list.value.length >= total.value
    }
  } catch (err) {
    error.value = true
  }
  loading.value = false
  refreshing.value = false
}

const onLoad = () => {
  setTimeout(() => {
    pageData.page++
    getList()
  }, 500)
}

const onRefresh = () => {
  list.value = []
  pageData.page = 1
  setTimeout(() => {
    getList()
    refreshing.value = false
  }, 500)
}

const handleFavorite = async (row: any) => {
  const { data } = await cancelFavorite({ menu_id: row.menu_id })
  if (data.code === 0) {
    list.value = list.value.filter(item => item.id !== row.id)
    total.value = total.value - 1

    // 如果当前页数据为空且不是第一页，则自动加载上一页数据
    if (list.value.length === 0 && pageData.page > 1) {
      pageData.page--
      getList()
    }
  }
}

// 滚动时显示滚动条
const handleScroll = () => {
  if (favoriteScrollWrap.value) {
    // 现代浏览器：修改滚动条颜色
    favoriteScrollWrap.value.style.scrollbarColor = 'rgba(191, 191, 191, 0.8) rgba(191, 191, 191, 0.2)'

    // 清除自动隐藏的定时器
    if (window.scrollBarTimer) {
      clearTimeout(window.scrollBarTimer)
    }

    // 滚动停止后，延迟隐藏滚动条
    window.scrollBarTimer = setTimeout(() => {
      favoriteScrollWrap.value!.style.scrollbarColor = 'rgba(0, 0, 0, 0) rgba(0, 0, 0, 0.1)'
    }, 500)
  }
}

onMounted(() => {
  getList()
  if (favoriteScrollWrap.value) {
    favoriteScrollWrap.value.addEventListener('scroll', handleScroll)
  }
})

onUnmounted(() => {
  if (favoriteScrollWrap.value) {
    favoriteScrollWrap.value.removeEventListener('scroll', handleScroll)
    clearTimeout(window.scrollBarTimer)
  }
})
</script>

<style lang="scss" scoped>
.pageBox {
  background: #ffffff;
  padding-top: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .favorite-wrapper {
    flex: 1;
    overflow-y: auto;
    scrollbar-width: thin;
    padding: 0 20px;
    scrollbar-color: rgba(0, 0, 0, 0) rgba(0, 0, 0, 0.1);
    transition: scrollbar-color 0.3s ease;

    // WebKit 内核浏览器
    &::-webkit-scrollbar {
      width: 4px;
    }

    &::-webkit-scrollbar-track {
      background: rgba(0, 0, 0, 0.1);
      // 轨道浅灰色
    }

    &::-webkit-scrollbar-thumb {
      background-color: rgba(0, 0, 0, 0);
      // 初始透明
      border-radius: 2px;
      transition: background-color 0.3s ease;
    }

    &:hover::-webkit-scrollbar-thumb,
    &:scrollbarthumbvertical::-webkit-scrollbar-thumb {
      background-color: rgba(0, 0, 0, 0.4);
    }

    .favorite {
      width: 100%;

      .food-item {
        padding: 15px;
        margin-bottom: 15px;
        border-bottom: 1px solid #f5f5f5;
        border-radius: 10px;

        &:last-child {
          margin-bottom: 0;
        }

        .img-box {
          width: 120px;
          height: 120px;
          border-radius: 50%;
          overflow: hidden;
          background: #f5f5f5;
        }

        .food-img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
    }
  }
}
</style>